<template>
  <PageWrapper dense>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <RadioGroup v-model:value="queryStatus">
          <RadioButton value="0">全部</RadioButton>
          <RadioButton value="1">已上架</RadioButton>
          <RadioButton value="2">已下架</RadioButton>
        </RadioGroup>
        <a-button @click="downloadExcel(exportProduct, '产品数据')" v-auth="'product:product:export'">导出</a-button>
        <a-button type="primary" @click="handleAdd" v-auth="'demo:demo:add'">新增</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'spuName'">
          <a-button type="link" size="small" @click="handleDetail(record)">{{
            record.spuName
          }}</a-button>
        </template>
        <template v-if="column.dataIndex === 'productLabel'">
          <Space :size="2">
            <Tag v-for="item in record.productLabel.split(',')" :key="item" color="green">{{
              item
            }}</Tag>
          </Space>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction stopButtonPropagation :actions="[
            {
              label: '修改',
              icon: IconEnum.EDIT,
              type: 'primary',
              ghost: true,
              auth: 'product:product:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              label: record.followStatus ? '下架' : '上架',
              icon: record.followStatus ? IconEnum.UNLOCK : IconEnum.LOCK,
              type: 'primary',
              ghost: true,
              ifShow: true,
              onClick: handleFollow.bind(null, record),
            },
            {
              label: '删除',
              icon: IconEnum.DELETE,
              type: 'primary',
              danger: true,
              ghost: true,
              auth: 'product:product:remove',
              popConfirm: {
                placement: 'left',
                title: '是否删除产品[' + record.spuName + ']?',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]" />
        </template>
      </template>
    </BasicTable>
  </PageWrapper>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { downloadExcel } from '@/utils/file/download';
import { Tag, Space, RadioGroup, RadioButton } from 'ant-design-vue';
import { PageWrapper } from '@/components/Page';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { listProduct, delProduct, updateProductFllow, exportProduct } from '@/api/product';
import { useGo } from '@/hooks/web/usePage';
import { formSchems, columns } from './product.data';
import { IconEnum } from '@/enums/appEnum';
import { PageEnum } from '@/enums/pageEnum';
import { useUserStoreWithOut } from '@/store/modules/user';
defineOptions({ name: 'Product' });
const queryStatus = ref<string>('0');
const userStore = useUserStoreWithOut();
const [registerTable, { reload }] = useTable({
  title: '产品列表',
  api: listProduct,
  showIndexColumn: false,
  rowKey: 'id',
  useSearchForm: true,
  formConfig: {
    schemas: formSchems,
    baseColProps: {
      span: 6,
    },
  },
  beforeFetch: (params: Recordable) => {
    params.queryStatus = queryStatus.value;
    if (params.dateRange) {
      params.beignTime = params.dateRange[0];
      params.endTime = params.dateRange[1];
      delete params.dateRange;
    }
    return params;
  },
  afterFetch(data: Recordable[]) {
    const newData = data.map((item) => {
      return {
        ...item,
        followStatus: item.followerIds
          ? item.followerIds.split(',').findIndex((item) => item == userStore.userInfo?.userId) >
          -1
          : false,
      };
    });
    return newData;
  },
  columns: columns,
  actionColumn: {
    width: 260,
    title: '操作',
    key: 'action',
    fixed: 'right',
  },
});
watch(
  () => queryStatus.value,
  () => {
    reload();
  },
);
const go = useGo();
function handleDetail(record: Recordable) {
  go({ path: '/product/productDetail' as PageEnum, query: { id: record.spuId } });
}
function handleEdit(record: Recordable) {
  go({
    path: '/product/productEdit' as PageEnum,
    query: { id: record.spuId, type: 'update' },
  });
}

function handleAdd() {
  go({ path: '/product/productEdit' as PageEnum, query: { type: 'add' } });
}

async function handleFollow(record: Recordable) {
  let followerIds = <string | number | undefined>'';
  if (record.followStatus) {
    followerIds = record.followerIds
      .split(',')
      .filter((item: any) => item != userStore.userInfo?.userId)
      .join(',');
  } else {
    followerIds = record.followerIds + ',' + userStore.userInfo?.userId;
  }
  await updateProductFllow(record.spuId, followerIds);
  await reload();
}

async function handleDelete(record: Recordable) {
  await delProduct(record.spuId);
  await reload();
}
</script>

<style scoped></style>
